package com.anyikang.volunteer.sos.volunteer.app.sos;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;

import com.anyikang.volunteer.sos.volunteer.R;
import com.anyikang.volunteer.sos.volunteer.app.MyApplication;
import com.anyikang.volunteer.sos.volunteer.app.MyConstant;
import com.anyikang.volunteer.sos.volunteer.app.adapter.SosRecordAdapter;
import com.anyikang.volunteer.sos.volunteer.app.bean.SosListData;
import com.anyikang.volunteer.sos.volunteer.app.bean.SosListItem;
import com.anyikang.volunteer.sos.volunteer.app.bean.SosListJson;
import com.anyikang.volunteer.sos.volunteer.app.bean.TaskOrder;
import com.anyikang.volunteer.sos.volunteer.app.bean.User;
import com.anyikang.volunteer.sos.volunteer.app.main.MainActivity;
import com.anyikang.volunteer.sos.volunteer.app.spot.SpotFragment;
import com.anyikang.volunteer.sos.volunteer.app.view.MyScrollListView;
import com.anyikang.volunteer.sos.volunteer.app.view.RefreshScrollviewLayout;
import com.anyikang.volunteer.sos.volunteer.utils.MyErrorDeal;
import com.anyikang.volunteer.sos.volunteer.utils.ToastUtils;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import org.json.JSONObject;

import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author xw.gao
 * @version 2017/6/17
 * @git http://60.205.139.138:81/root/GSMServerAPP.git
 */
public class HelpAllStateFragment extends SpotFragment implements SwipeRefreshLayout.OnRefreshListener,
        RefreshScrollviewLayout.OnLoadListener {

    MyScrollListView lvRecords;
    RefreshScrollviewLayout swipeLayout;

    String TAG = "HelpAllStateFragment";

    private ArrayList<SosListItem> mSosList = new ArrayList<SosListItem>();
    SosRecordAdapter mAdapter;
    private View layout;
    int pageIndex = 1;
    private boolean hasNextPage = false;
    private Activity mActivity;
    private Handler mHandler;

    private final int REFRESH_LIST = 0;  //刷新列表
    private final int LOAD_MORE = 1;   //加载更多
    int pageSize = 20;

    // TODO: Rename and change types and number of parameters
    public static HelpAllStateFragment newInstance(String userId) {
        HelpAllStateFragment fragment = new HelpAllStateFragment();
        Bundle args = new Bundle();
        args.putString("userId", userId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        if (layout == null) {
            layout = inflater.inflate(R.layout.fragment_help_all, container, false);
        }

        createHandler();
        initView();
        autoRefresh(); //自动刷新

        Log.i(TAG, "onCreateView");
        return layout;
    }


    /**
     * 获取成功
     */
    public void  dealGetSuccess(SosListData data,int operation) {

        hasNextPage = data.isHasNextPage();

        if (operation == REFRESH_LIST)
        {
            if(mSosList != null)
            {
                mSosList.clear();
            }
        }

        ArrayList<SosListItem> sosListItem =  data.getList();

        if(sosListItem!=null && sosListItem.size()>0)
        {
            mSosList.addAll(sosListItem);
        }
        mAdapter.notifyDataSetChanged();


        if(hasNextPage)
        {
          //gxw-  hasNextPage = true;
            pageIndex++;
        }
        else {
            //gxw- hasNextPage = false;
        }
        return;
    }

    /**
     * 获取服务端 任务单全部状态的数据
     */
    private void getData(final int operation) {


        User user = new User(mActivity);
        String token = user.getUserToken();


        Log.i(TAG,"url ="+ MyConstant.API_SOS_LIST + "tokenId="+token+",type="+operation+",pageIndex="+pageIndex+",pageSize="+pageSize);
        OkHttpUtils
                .get(MyConstant.API_SOS_LIST)//
                .tag(MyConstant.API_SOS_LIST)//
                .params("tokenId", token)//
                .params("pageIndex", String.valueOf(pageIndex))//
                .params("pageSize", String.valueOf(pageSize))//
                .params("type",String.valueOf(0))
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        mHandler.sendEmptyMessage(0);

                        int retCode = response.code();
                        if(retCode == 200)
                        {
                            Log.i(TAG,"onSuccess 200 return："+s);
                            try
                            {
                                SosListJson sosListJson = new Gson().fromJson(s,SosListJson.class);

                                if(sosListJson.getStatus() == 1)//查询全部状态成功
                                {
                                    //登录成功
                                    dealGetSuccess(sosListJson.getData(),operation);
                                }
                                else {
                                    String msg = sosListJson.getMsg();
                                    MyErrorDeal.dealError(msg,mActivity);
                                }
                            }
                            catch (Exception e)
                            {
                                e.printStackTrace();
                            }
                        }
                        else
                        {
                            MyErrorDeal.dealHttpError(response,mActivity);
                            Log.i(TAG,"onSuccess "+retCode+"return: "+s);
                        }
                    }

                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        mHandler.sendEmptyMessage(0);
                        MyErrorDeal.dealHttpError(response,mActivity);

                    }
                });
    }


    /**
     * 检查任务单状态
     */

    public void checkTaskOrderState(final SosListItem sosItem)
    {
        if(MyApplication.isRecvingOrder)
        {
            String helpingTip = mActivity.getResources().getString(R.string.helping);
            ToastUtils.showToast(mActivity,helpingTip);
            return;
        }
        User user = new User(mActivity);
        String token = user.getUserToken();
        String taskOrderId = sosItem.getItemId();



        Log.i(TAG,"url ="+ MyConstant.API_GET_TASK_STATE + "tokenId="+token+",itemId="+taskOrderId);
        OkHttpUtils
                .get(MyConstant.API_GET_TASK_STATE)//
                .tag(MyConstant.API_GET_TASK_STATE)//
                .params("tokenId", token)//
                .params("itemId",taskOrderId)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {

                        swipeLayout.setRefreshing(false);
                        swipeLayout.setLoading(false);
                        int retCode = response.code();
                        if(retCode == 200)
                        {
                            Log.i(TAG,"onSuccess 200 return："+s);
                            try
                            {
                                JSONObject selectTaskOrder = new JSONObject(s);
                                int status = selectTaskOrder.getInt("status");

                                if(status == 1)//查询成功
                                {
                                    JSONObject data = selectTaskOrder.getJSONObject("data");
                                    int taskOrderState = data.getInt("state");
                                    switch (taskOrderState)
                                    {
                                        case 1:   //需要救助
                                            TaskOrder taskOrder = new TaskOrder();
                                            taskOrder.setItemId(sosItem.getItemId());
                                            taskOrder.setSosTime(sosItem.getSosTime());
                                            taskOrder.setDeviceIMEI(sosItem.getDeviceIMEI());
                                            taskOrder.setLatitude(sosItem.getLatitude());
                                            taskOrder.setLongitude(sosItem.getLongitude());
                                            taskOrder.setAddress(sosItem.getAddress());
                                            taskOrder.setName(sosItem.getName());
                                            //gxw-taskOrder.setSosPersonId(sosItem.getSosPersonId());暂不传递，没接单前不允许查求救人信息
                                            //gxw- 呼救列表少个报警类型，不现在没有用  taskOrder.setAlarmType(sosItem.alarmTpe);
                                            Intent i = new Intent(mActivity, MainActivity.class);
                                            i.putExtra("from","help");
                                            i.putExtra("taskOrder",taskOrder);
                                           i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK );
                                            startActivity(i);
                                            break;
                                        case 2:  //救助中
                                            boolean isSelfReceive = data.getBoolean("isSelfReceive");
                                            String tip;
                                            if(isSelfReceive)
                                            {
                                               tip="该任务单我已经在救助中，不能再接受";
                                            }
                                            else
                                            {
                                                tip="该任务单别人已经在救助中，不能再接受";
                                            }
                                            ToastUtils.showToast(mActivity,tip);


                                            break;
                                        case 3: //已完成

                                            break;
                                    }

                                }
                                else {
                                    //查询失败
                                    String msg = selectTaskOrder.getString("msg");
                                    MyErrorDeal.dealError(msg,mActivity);

                                }
                            }
                            catch (Exception e)
                            {
                                e.printStackTrace();
                            }
                        }
                        else
                        {
                            MyErrorDeal.dealHttpError(response,mActivity);
                            Log.i(TAG,"onSuccess "+retCode+"return: "+s);
                        }
                    }

                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        swipeLayout.setRefreshing(false);
                        swipeLayout.setLoading(false);
                        MyErrorDeal.dealHttpError(response,mActivity);

                    }
                });


    }

    public void dealItemClick(int position)
    {
        SosListItem sosItem = mSosList.get(position);
        int state = sosItem.getState();

        switch (state)
        {
            case 1:  //需要救援
                checkTaskOrderState(sosItem);

                break;

            case 2:
                ToastUtils.showToast(mActivity,"已在救助中了，无需救援");
                break;

            case 3:
                ToastUtils.showToast(mActivity,"救助已完成了，无需救援");
               break;

        }

    }
    /**
     * 初始化视图
     */
    private void initView() {

        lvRecords = (MyScrollListView) layout.findViewById(R.id.lvRecords);
        mAdapter = new SosRecordAdapter(mSosList,mActivity,"");
        lvRecords.setAdapter(mAdapter);
        lvRecords.setOverscrollHeader(getResources().getDrawable(R.mipmap.ic_launcher));
        lvRecords.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

                dealItemClick(position);

            }
        });


        swipeLayout = (RefreshScrollviewLayout) layout.findViewById(R.id.swipe_container);
        swipeLayout.setLoadingLayout((LinearLayout)layout.findViewById(R.id.listLayout));
        swipeLayout.setColorSchemeResources(R.color.color_bule,
                R.color.green,
                R.color.color_bule,
                R.color.green_50bc31);
        swipeLayout.setSize(SwipeRefreshLayout.DEFAULT);
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setOnLoadListener(this);
    }

    public void createHandler()
    {
        mHandler = new Handler() {
            @Override
            public void handleMessage(android.os.Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 0:
                        swipeLayout.setRefreshing(false);
                        swipeLayout.setLoading(false);
                        break;
                    default:
                        Log.i(TAG, "Unhandled msg - " + msg.what);
                }
            }
        };
    }


    @Override
    public void onAttach(Context context) {
        mActivity = (Activity) context;
        super.onAttach(context);
    }


    /**
     * 回到页面自动刷新
     */
    public void autoRefresh()
    {
        swipeLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeLayout.setRefreshing(true);

            }
        });
        hasNextPage = true;
        pageIndex = 1;
        getData(REFRESH_LIST);//刷新页面
    }

    @Override
    public void onResume() {
        Log.i(TAG,"onResume");
        //GXW- getData(REFRESH_LIST);//刷新页面
        super.onResume();
    }


    @Override
    public void onDestroyView() {

        Log.i(TAG,"onDestroyView");
        if (layout != null) {
            ((ViewGroup) layout.getParent()).removeView(layout);
        }
        super.onDestroyView();

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
     /*   Log.i(TAG,"onHiddenChanged"+hidden);
        if(hidden == false)
        {
            autoRefresh();
        }*/
        super.onHiddenChanged(hidden);
    }

    @Override
    public void onRefresh() {
        Log.i(TAG,"onRefresh");
        hasNextPage = true;
        pageIndex = 1;
        getData(0);

    }

    @Override
    public void onLoad() {   //上拉加载更多

        Log.i(TAG,"onLoad");
        if(hasNextPage)
        {
            getData(LOAD_MORE);
        }
        else {
            swipeLayout.setLoading(false);
        }

    }
}
